package cn.swu.ws;

import jakarta.servlet.FilterChain;

import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;

import java.io.IOException;

public class LoginFilter extends HttpFilter {
    private String[] ignoreUrls = null;
    public void init(FilterConfig filterConfig){
        String urls = filterConfig.getInitParameter("ignoreUrls");
        if (urls != null) {
            this.ignoreUrls = urls.split(";");
        }
        for (String ignoreUrl : ignoreUrls) System.out.println(ignoreUrl);
    }
    public void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletException, IOException {
        for (String ignoreUrl : this.ignoreUrls) {
            if (req.getRequestURI().endsWith(ignoreUrl)) {
                chain.doFilter(req, resp);
                return;
            }
        }

        HttpSession session=req.getSession(true);
        LoginState loginState= (LoginState) session.getAttribute("loginState");
        if(loginState!=null&&loginState.equals(LoginState.LOGIN_SUCCESS)){
           chain.doFilter(req,resp);
           return;
        }else {
            resp.sendRedirect("./index.html");
            return;
        }
    }
}
